package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;
import com.lagou.rpc.consumer.zk.ZkUtil;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Proxy;
import java.util.List;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
public class RpcClientProxy {

    static ZkUtil zkUtil = new ZkUtil();

    static int count = 0;

    static String zkServer;

    public static Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, (proxy, method, args) -> {
                    //1.封装request请求对象
                    RpcRequest rpcRequest = new RpcRequest();
                    rpcRequest.setRequestId(UUID.randomUUID().toString());
                    rpcRequest.setClassName(method.getDeclaringClass().getName());
                    rpcRequest.setMethodName(method.getName());
                    rpcRequest.setParameterTypes(method.getParameterTypes());
                    rpcRequest.setParameters(args);
                    //2.创建RpcClient对象
                    RpcClient rpcClient = getRpcClient();
                    try {
                        long start = System.currentTimeMillis();


                        //3.发送消息
                        Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                        RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                        long end = System.currentTimeMillis();
                        if (rpcResponse.getError() != null) {
                            throw new RuntimeException(rpcResponse.getError());
                        }
                        zkUtil.updateData(zkServer, end - start);
                        //4.返回结果
                        Object result = rpcResponse.getResult();
                        return JSON.parseObject(result.toString(), method.getReturnType());
                    } catch (Exception e) {
                        throw e;
                    }

                });
    }

    /**
     * 根据每次调用，进行计数
     */
    private static RpcClient getRpcClient() {

        List<String> serverList = zkUtil.getNode();
        if (CollectionUtils.isEmpty(serverList)) {
            throw new RuntimeException("没有服务端可调用！");
        }
        String server = serverList.get(nextIndex(serverList));
        zkServer = server;
        String[] split = server.split("-");
        System.out.println("使用当前地址进行调用：" + server);
        return new RpcClient(split[0], Integer.parseInt(split[1]));
    }

    public static synchronized int nextIndex(List<String> serverList) {
        try {
            return count;
        } finally {
            if (serverList.size() - 1 < ++count) {
                count = 0;
            }
        }
    }
}
